/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package outToR;

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import units.CellType;
import units.DifferentialExpression;
import units.DifferentialExpressionLibrary;
import units.ExpressionLibrary;
import units.DiseaseStage;
import units.Gene;
import units.GeneLibrary;
import units.MonkeyType;
import utils.FileUtils;

/**
 *
 * @author jamie
 */
public class SeparateClustOutput {

    private DifferentialExpressionLibrary del;
    private File outputFolder = new File("/Users/jamie/monkeys/outputForR/clust/");
    private double maxP = 0.05;

    public SeparateClustOutput() {

        GeneLibrary library = new GeneLibrary();

        del = new DifferentialExpressionLibrary();
        del.populateForAllMonkeyTypes(library);
        library.populateGeneSymbols();
    }

    public void makeAllHClustOutput() {
        for (DiseaseStage ds : DiseaseStage.values()) {
            for (MonkeyType mt : MonkeyType.values()) {
                for (CellType ct : CellType.values()) {

                    System.out.println("running output for " + ds.name() + ", " + mt.name());
                    try {
                        makeHClustOutput(ds, mt, ct);
                    } catch (IOException ex) {
                        Logger.getLogger(SeparateClustOutput.class.getName()).log(Level.SEVERE, null, ex);
                    }

                }
            }
        }
    }

    public void makeHClustOutput(DiseaseStage ds, MonkeyType mt, CellType ct) throws IOException {
        File outputFile = new File(outputFolder, ds.name() + "_" + mt.name() + "_" + ct.name() + ".txt");
        BufferedWriter writer = FileUtils.getBufferedWriter(outputFile);
        TreeMap<Integer, List<DifferentialExpression>> deGenes = del.getDifferentialExpressedGenes(mt, ct, ds, maxP);
        List<Integer> timePoints = del.getTimePoints(mt, ds);
        System.out.println("there are " + timePoints.size() + " timePoints in ds " + ds.name());
        for (int probeId : deGenes.keySet()) {
            StringBuffer valuesBuffer = new StringBuffer();

//            System.out.println(g.getSymbol());

            valuesBuffer.append(probeId + "\t");
            for (int timePoint : timePoints) {


                for (DifferentialExpression de : deGenes.get(probeId)) {
                    if (de.getTimePoint() == timePoint && de.getCellType().equals(ct)) {

                        valuesBuffer.append(de.getLogExp() + "\t");

                    }
                }

            }
            writer.append(valuesBuffer.toString().trim() + "\n");
        }
        writer.close();
    }
}
